#!/usr/bin/env sh

# Script to deploy certificates to Tencent CDN

# The following variables exported from environment will be used.
# If not set then values previously saved in domain.conf file are used.
#
#
# export DEPLOY_TENCENT_CDN_ID=""  # access key id
# export DEPLOY_TENCENT_CDN_SECRET=""  # access key secret
# export DEPLOY_TENCENT_CDN_DOMAINS=""  # domains, used for SAN or wildcard certificate

########  Public functions #####################
tencent_cdn_deploy() {
  _cdomain="$1"
  _ckey="$2"
  _ccert="$3"
  _cca="$4"
  _cfullchain="$5"

  _debug _cdomain "$_cdomain"
  _debug _ckey "$_ckey"
  _debug _ccert "$_ccert"
  _debug _cca "$_cca"
  _debug _cfullchain "$_cfullchain"

  # access key id is required to access tencent api. 
  _migratedeployconf Le_Deploy_tencent_cdn_id DEPLOY_TENCENT_CDN_ID
  _getdeployconf DEPLOY_TENCENT_CDN_ID
  _debug2 DEPLOY_TENCENT_CDN_ID "$DEPLOY_TENCENT_CDN_ID"
  if [ -z "$DEPLOY_TENCENT_CDN_ID" ]; then
    _err "DEPLOY_TENCENT_CDN_ID not defined."
    return 1
  fi
  _savedeployconf DEPLOY_TENCENT_CDN_ID "$DEPLOY_TENCENT_CDN_ID" 

  # access key secret is required to access tencent api. 
  _migratedeployconf Le_Deploy_tencent_cdn_secret DEPLOY_TENCENT_CDN_SECRET
  _getdeployconf DEPLOY_TENCENT_CDN_SECRET
  _debug2 DEPLOY_TENCENT_CDN_SECRET "$DEPLOY_TENCENT_CDN_SECRET"
  if [ -z "$DEPLOY_TENCENT_CDN_SECRET" ]; then
    _err "DEPLOY_TENCENT_CDN_SECRET not defined."
    return 1
  fi
  _savedeployconf DEPLOY_TENCENT_CDN_SECRET "$DEPLOY_TENCENT_CDN_SECRET" 

  # domain names is required when deploy SAN or wildcard cert.
  _migratedeployconf Le_Deploy_tencent_cdn_domains DEPLOY_TENCENT_CDN_DOMAINS
  _getdeployconf DEPLOY_TENCENT_CDN_DOMAINS
  _debug2 DEPLOY_TENCENT_CDN_DOMAINS "$DEPLOY_TENCENT_CDN_DOMAINS"
  if [ -z "$DEPLOY_TENCENT_CDN_DOMAINS" ]; then
    DEPLOY_TENCENT_CDN_DOMAINS=$_cdomain
  fi
  _adomains="`echo $DEPLOY_TENCENT_CDN_DOMAINS`"
  _savedeployconf DEPLOY_TENCENT_CDN_DOMAINS "$DEPLOY_TENCENT_CDN_DOMAINS"

  _tencent_cdn_deploy

  _err_code="$?"
  return $_err_code
}

_tencent_cdn_deploy() {
  cmd="$DEFAULT_INSTALL_HOME/deploy/tencent_deploy.py"                  
  for domain in $(echo "$_adomains" | tr ',' " ");do
    python3 $cmd -i $DEPLOY_TENCENT_CDN_ID -s $DEPLOY_TENCENT_CDN_SECRET -d $domain -c "$_cfullchain" -k "$_ckey"
    _err_code="$?"
    if [ "$_err_code" -ne 0 ];then
      return $_err_code
    fi
  done

  return 0
}
